<?php

namespace app\common\model\base;

use app\common\model\BaseModel;

class PatchModel extends BaseModel {

    protected $table = 'patch';

    /**
     * 格式化列表
     * @param $list
     * @return array
     */
    public function _formatList($list) {
        $dict       = DictItemModel::where('class_code', '10.02')->column('dict_value', 'dict_code');
        foreach ($list as $k => $v) {
            $list[$k]['patch_type_str'] = $dict[$v['patch_type']] ?? '';
        }
        return $list;
    }

    /**
     * 添加
     * @param $data
     * @return PatchModel|\think\Model
     * @throws \Exception
     */
    public function add($data) {
        $content = $data['patch_content_'.$data['patch_type']];
        if($data['patch_type']==6){
            $content = array_values($data['patch_content_6']);
            $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        }
        $data['patch_content'] = $content;
        if($this->where('patch_sn', $data['patch_sn'])->find()) exception('碎片编码已存在');
        return self::create($data);
    }

    /**
     * 编辑
     * @param $data
     * @return PatchModel
     * @throws \Exception
     */
    public function edit($data){
        $info = $this->where('id',$data['id'])->find();
        $content = $data['patch_content_'.$info['patch_type']];
        if($info['patch_type']==6){
            $content = array_values($data['patch_content_6']);
            $content = json_encode($content, JSON_UNESCAPED_UNICODE);
        }
        $data['patch_content'] = $content;
        if ($info['patch_sn'] != $data['patch_sn']) {
            if ($this->where('patch_sn', $data['patch_sn'])->find()) exception('碎片编码已存在');
        }
        return self::update($data);
    }

    /**
     * 删除
     * @param $id
     */
    public function del($id){
        $this->where('id',$id)->delete();
    }
}